﻿using Cysharp.Threading.Tasks;
using System;
using System.Threading;
using UnityEngine;

namespace Bullet
{
    public class BulletMove : MonoBehaviour
    {
        public float Speed { get; set; }
        public float LifeTime { get; set; }
        public bool IsAlive { get; set; }


        private CancellationTokenSource _timerSource;
        
        private void Start()
        {
            _timerSource  = new CancellationTokenSource();
            IsAlive = true;
            ThrowBullet().Forget();
        }

        private async UniTaskVoid ThrowBullet()
        {
            await UniTask.Delay(TimeSpan.FromSeconds(LifeTime), cancellationToken: _timerSource.Token);
            if (!IsAlive) 
                return;
            if (gameObject)
                Destroy(gameObject);
        }

        private void FixedUpdate()
        {
            if (!IsAlive) 
                return;
            transform.position += transform.forward * Speed;
        }

        private void OnDestroy()
        {
            _timerSource?.Cancel();
            _timerSource?.Dispose();
        }
    }
}